import React from 'react';
import { message, Popconfirm, Button } from 'antd';
import { connect } from 'umi';
import AuthComponent from '@/utils/auth/AuthComponent';
import { Icon } from '../components';
import { quickAccept } from '../service';

const CONFIRM_MAP = {
    2: '需求已分配',
    3: '负责人变更中'
};
function DemandAccept({ data, user, onSuccess = () => {}, antButton, ...rest }) {
    const { preparePrincipalEmployeeName, principalEmployeeCode, recruitStatus } = data;
    const { employeeCode, employeeName } = user;
    const renderButton = React.useCallback(
        props => {
            const label = '一键认领';
            if (!antButton) {
                return <Icon title={label} type="yijianrenling" {...props} />;
            }
            return (
                <Button type="primary" {...props}>
                    {label}
                </Button>
            );
        },
        [antButton]
    );
    const handleUpdate = async () => {
        try {
            const res = await quickAccept({
                recruitStatus: 3,
                id: data.id,
                principalChangeReason: '',
                principalEmployeeCode: employeeCode,
                principalEmployeeName: employeeName
            });
            if (res.code === 10000) {
                message.success('认领成功！');
                onSuccess();
            } else {
                message.error(res?.msg);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const isCurrentPrincipal = user.employeeCode === principalEmployeeCode;

    return (
        <AuthComponent code="office:recruitment:course:requirement:principal:add">
            {preparePrincipalEmployeeName ? (
                <Popconfirm
                    disabled={!preparePrincipalEmployeeName}
                    placement="bottomRight"
                    title={`${CONFIRM_MAP[recruitStatus]}，待${preparePrincipalEmployeeName}接受，是否继续修改`}
                    onConfirm={() => {
                        if (!isCurrentPrincipal) {
                            handleUpdate();
                        }
                    }}
                    okText="是"
                    cancelText="否"
                >
                    {renderButton(rest)}
                </Popconfirm>
            ) : (
                renderButton({ ...rest, onClick: handleUpdate })
            )}
        </AuthComponent>
    );
}
export default connect(({ user }) => ({ user: user.currentUser }))(DemandAccept);
